<template>
  <van-nav-bar
    title="购物车"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />

  <van-checkbox-group v-model="selectProducts" ref="checkboxGroup">
    <van-swipe-cell v-for="item in products">
      <van-row>
        <van-col span="2" class="leftbox">
          <van-checkbox :name="item"></van-checkbox>
        </van-col>
        <van-col span="22">
          <van-card
            :price="item.productPrice"
            :desc="item.productSubtitle"
            :title="item.productName"
            :thumb="item.productImg"
          >
            <template #num>
              <van-stepper
                v-model="item.productQty"
                @change="changeQty(item)"
              />
            </template>
          </van-card>
        </van-col>
      </van-row>
      <template #right>
        <van-button
          square
          text="删除"
          type="danger"
          class="delete-button"
          @click="delCart(item, index)"
        />
      </template>
    </van-swipe-cell>
  </van-checkbox-group>
  <van-empty description="购物车空空如也" v-if="products.length === 0" />
  <van-submit-bar
    :price="totalAmount"
    button-text="提交订单"
    @submit="onSubmit"
  >
    <van-checkbox v-model="selectAll" @change="checkAll">全选</van-checkbox>
  </van-submit-bar>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { productApi, cartApi } from "@/api/index";
import { showToast,showSuccessToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import {appStore}  from '@/store/appStore'
import {storeToRefs}  from "pinia"

//把存储对象转成引用对象
let { userId,phone} =   storeToRefs(appStore())
const route = useRoute();
const router = useRouter();

const selectProducts = ref([]); //勾选的商品
const selectAll = ref(false); //是否勾选所有商品
const totalAmount = ref(0); //总计钱数
//购物车商品列表
const products = ref([]);

const checkboxGroup = ref(null);

//钩子函数
onMounted(() => {
  if(userId.value===0){
    router.push({name:"user-login"})
    showSuccessToast("请先登录")
    return
  }
  callProductApi();
});

//查询购物车商品api
const callProductApi = () => {
  cartApi.select.call({ userId: userId.value }).then((res: any) => {
    products.value = res;
    selectProducts.value = res;
  });
};

//计算勾选商品的总额
const computeTotalAmount = () => {
  totalAmount.value = 0;

  selectProducts.value.forEach((item: any) => {
    totalAmount.value += item.productPrice * item.productQty * 100;
  });
};

//监视勾选的商品，如果有变化就重新计算总额
watch(
  () => selectProducts.value,
  (newValue, oldValue) => {
    //如果勾选的商品和购物车所有商品的数量一样，那么就等于全选
    if (products.value.length > 0) {
      selectAll.value = selectProducts.value.length === products.value.length;
    }

    //重新计算总额
    computeTotalAmount();
  },
  { immediate: true }
);

//改变数量
const changeQty=(item:any)=>{
  cartApi.changeQty.call({id:item.id,productQty:item.productQty}).then((res:any)=>{
    //重新计算总价
    computeTotalAmount()
  })
}

//删除购物车数据
const delCart=(item:any,index:number)=>{
  cartApi.delCart.call({id:item.id}).then(()=>{
    showSuccessToast("删除成功")
    products.value.splice(index,1)
    //computeTotalAmount()
    callProductApi();
  })
}
//全选按钮
const checkAll = (b: boolean) => {
  if (b === true) {
    checkboxGroup.value.toggleAll(true);
  }
};

//提交结算
const onSubmit = () => {
   const cartIds = selectProducts.value.map((item: any) => {
        return item.id
    })

    if(cartIds.length === 0){
        showToast("请选择商品")
      return
    }
  router.push({name:"ordering",query:{cartIds:cartIds}})
};

//点击返回上一级
const onClickLeft = () => history.back();
</script>

<style scoped>
.leftbox {
  height: 100px;
  display: flex;
  align-items: center;
  justify-self: center;
}

.delete-button {
  height: 100%;
}
</style>